package com.study.controller;

import com.study.service.UserService;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * @Author tanglingyu
 * @Date: 2021/09/09/ 15:15
 * @Description
 */
@RestController
public class TestController6 {

  @Autowired
  private UserService userService;

  @RequestMapping(value = "/file", method = RequestMethod.POST)
  public String importHX(HttpServletRequest request, HttpServletResponse response) {
    try {
      CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      if (multipartResolver.isMultipart(request)) {
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
          MultipartFile file = multiRequest.getFile(iter.next().toString());
          String code = getFileEncode2(file.getInputStream());
          if ("asci".equals(code)) {
            // 这里采用GBK编码,而不用环境编码格式,因为环境默认编码不等于操作系统编码
            // code = System.getProperty("file.encoding");
            code = "GBK";
          }
          BufferedReader bufferedReader = new BufferedReader(
              new InputStreamReader(file.getInputStream()));
          String s = null;
          while ((s = bufferedReader.readLine()) != null) {
            System.out.println(s);
//            final String s1 = new String(s.getBytes(), "utf-8");
            userService.insert(s, s, s);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "sb";
  }

  private String getFileEncode2(InputStream in) {
    String charset = "asci";
    byte[] first3Bytes = new byte[3];
    BufferedInputStream bis = null;
    try {
      boolean checked = false;
      bis = new BufferedInputStream(in);
      bis.mark(0);
      int read = bis.read(first3Bytes, 0, 3);
      if (read == -1) {
        return charset;
      }
      if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
        charset = "Unicode";//UTF-16LE
        checked = true;
      } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
        charset = "Unicode";//UTF-16BE
        checked = true;
      } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB
          && first3Bytes[2] == (byte) 0xBF) {
        charset = "UTF8";
        checked = true;
      }
      bis.reset();
      if (!checked) {
        int len = 0;
        int loc = 0;
        while ((read = bis.read()) != -1) {
          loc++;
          if (read >= 0xF0) {
            break;
          }
          if (0x80 <= read && read <= 0xBF) //单独出现BF以下的，也算是GBK
          {
            break;
          }
          if (0xC0 <= read && read <= 0xDF) {
            read = bis.read();
            if (0x80 <= read && read <= 0xBF)
            //双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB编码内
            {
              continue;
            } else {
              break;
            }
          } else if (0xE0 <= read && read <= 0xEF) { //也有可能出错，但是几率较小
            read = bis.read();
            if (0x80 <= read && read <= 0xBF) {
              read = bis.read();
              if (0x80 <= read && read <= 0xBF) {
                charset = "UTF-8";
                break;
              } else {
                break;
              }
            } else {
              break;
            }
          }
        }
        //TextLogger.getLogger().info(loc + " " + Integer.toHexString(read));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return charset;
  }


  @RequestMapping(value = "/png", method = RequestMethod.POST)
  public String png(HttpServletRequest request) {
    try {
      CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      if (multipartResolver.isMultipart(request)) {
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
          MultipartFile file = multiRequest.getFile(iter.next());
          final byte[] bytes = file.getBytes();
          test(bytes);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "sb";
  }
  private String test(byte[] bytes) {
    byte b1, b2, b3, b4, b5;
    int i = 0;
    for (; i < bytes.length; i++) {
      b1 = bytes[i];
      b2 = bytes[i + 1];
      b3 = bytes[i + 2];
      b4 = bytes[i + 3];
      b5 = bytes[i + 4];
      if (b1 == (byte) 0x3C && b2 == (byte) 0x3F && b3 == (byte) 0x78 && b4 == (byte) 0x6D
          && b5 == (byte) 0x6C) {
        break;
      }
    }
    byte[] target = new byte[bytes.length - i];
    for (int j = i, k = 0; j < bytes.length; ++j, ++k) {
      target[k] = bytes[j];
    }
    final String data = new String(target);
    final int start = data.indexOf("<");
    final int end = data.lastIndexOf(">");
    final String xmlString = data.substring(start, end + 1);
    System.out.println(xmlString);
    return xmlString;
  }


}
